import { storage } from "@/config/upload";

const typeColor = (type: "default" | "primary" | "success" | "warning" | "danger" = "default"): string => {
  const colors = {
    default: "#35495E",
    primary: "#3488ff",
    success: "#43B883",
    warning: "#e6a23c",
    danger: "#f56c6c"
  };
  return colors[type];
};

const tool: Record<string, any> = {};

interface Document {
  webkitIsFullScreen?: boolean;
  mozFullScreen?: boolean;
  msFullscreenElement?: Element;
  webkitFullscreenElement?: Element;
  exitFullscreen?: () => Promise<void>;
  msExitFullscreen?: () => Promise<void>;
  mozCancelFullScreen?: () => Promise<void>;
  webkitExitFullscreen?: () => Promise<void>;
}

interface HTMLElement {
  requestFullscreen?: () => Promise<void>;
  msRequestFullscreen?: () => Promise<void>;
  mozRequestFullScreen?: () => Promise<void>;
  webkitRequestFullscreen?: () => Promise<void>;
}

/**
 * LocalStorage
 */
tool.local = {
  set(table: string, settings: unknown): void {
    try {
      const _set = JSON.stringify(settings);
      localStorage.setItem(table, _set);
    } catch (err) {
      console.error("Error setting localStorage:", err);
    }
  },
  get(table: string): unknown | null {
    try {
      const data = localStorage.getItem(table);
      return data ? JSON.parse(data) : null;
    } catch (err) {
      console.error("Error parsing localStorage:", err);
      return null;
    }
  },
  remove(table: string): void {
    localStorage.removeItem(table);
  },
  clear(): void {
    localStorage.clear();
  }
};

tool.viewImage = (path: string, defaultStorage = "LOCAL"): string => {
  const mode = (tool.local.get("site_storage_mode")?.toUpperCase() as keyof typeof storage) || defaultStorage;
  return storage[mode] + path;
};

tool.capsule = (
  title: string,
  info: string,
  type: "primary" | "default" | "success" | "warning" | "danger" = "primary"
): void => {
  console.log(
    `%c ${title} %c ${info} %c`,
    "background:#35495E; padding: 1px; border-radius: 3px 0 0 3px; color: #fff;",
    `background:${typeColor(type)}; padding: 1px; border-radius: 0 3px 3px 0; color: #fff;`,
    "background:transparent"
  );
};

/**
 * 对象转url参数
 * @param data
 * @param isPrefix
 */
tool.httpBuild = (data: Record<string, any>, isPrefix = false): string => {
  const prefix = isPrefix ? "?" : "";
  const _result = Object.entries(data).reduce((acc, [key, value]) => {
    if (value === "" || value === undefined || value === null) {
      return acc;
    }
    if (Array.isArray(value)) {
      value.forEach(_value => {
        acc.push(`${encodeURIComponent(key)}[]=${encodeURIComponent(_value)}`);
      });
    } else {
      acc.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
    }
    return acc;
  }, [] as string[]);
  return _result.length ? prefix + _result.join("&") : "";
};

export default tool;
